﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Model.DocumentDB.Manifest
{
    /// <summary>Manifest file.</summary>
    [XmlRoot("studio.documentdb.manifest")]
    public class XmlManifest
    {
        private const string URL = "https://studiodocdb.blob.core.windows.net/logistics/Manifest.xml";

        /// <summary>URI of the latest download.</summary>
        [XmlAttribute("downloadUri")]
        public string DownloadUri { get; set; }

        /// <summary>Collection of releases.</summary>
        [XmlArray("releases")]
        [XmlArrayItem("release", Type = typeof(XmlRelease))]
        public XmlRelease[] Releases { get; set; }

        /// <summary>Load the manifest from the cloud location.</summary>
        /// <returns>Manifest object.</returns>
        public static async Task<XmlManifest> LoadAsync()
        {
            try
            {
                var client = new WebClient();
                var content = await client.DownloadStringTaskAsync(URL);
                var serializer = new XmlSerializer(typeof(XmlManifest));
                var manifest = serializer.Deserialize(new StringReader(content)) as XmlManifest;

                return manifest;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>Returns newer releases (if any).</summary>
        /// <returns>Newer releases.</returns>
        public XmlRelease[] GetNewerReleases(Version currentVersion)
        {
            try
            {
                var newer = from r in Releases
                            let version = new Version(r.Version)
                            where version > currentVersion
                            orderby version
                            select r;

                return newer.ToArray();
            }
            catch
            {
                return new XmlRelease[0];
            }
        }
    }
}
